package com.qiujie.service;

import com.qiujie.dto.Response;
import com.qiujie.dto.ResponseDTO;
import com.qiujie.entity.AnnualLeave;
import com.qiujie.entity.Staff;
import com.qiujie.mapper.AnnualLeaveMapper;
import com.qiujie.mapper.StaffMapper;
import com.qiujie.util.SeniorityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Year;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AnnualLeaveService {

    @Autowired
    private AnnualLeaveMapper annualLeaveMapper;

    @Autowired
    private StaffMapper staffMapper;

    // 初始化年休假额度（修复构造函数问题）
    @Scheduled(cron = "0 0 0 1 1 *")
    @Transactional
    public void initAnnualLeave() {
        List<Staff> staffList = staffMapper.selectList(null);
        int currentYear = Year.now().getValue();

        staffList.forEach(staff -> {
            AnnualLeave exist = annualLeaveMapper.selectByStaffAndYear(staff.getId(), currentYear);
            if (exist == null) {
                annualLeaveMapper.insert(new AnnualLeave(
                        staff.getId(),
                        currentYear,
                        calculateAnnualLeaveDays(staff.getBirthday()),
                        0
                ));
            }
        });
    }


    // 计算年休假天数
    private int calculateAnnualLeaveDays(Date birthday) {
        int seniority = SeniorityUtil.calculate(birthday);

        if (seniority < 1) {
            return 0; // 入职未满12个月
        } else if (seniority >= 20) {
            return 15;
        } else if (seniority >= 10) {
            return 10;
        } else {
            return 5;
        }
    }

    // 获取剩余天数（返回标准响应格式）
    public ResponseDTO getRemainingDays(Integer staffId) {
        try {
            // 增加员工存在性校验
            Staff staff = staffMapper.selectById(staffId);
            if (staff == null) {
                return new ResponseDTO(404, "员工不存在");
            }

            AnnualLeave record = annualLeaveMapper.selectByStaffAndYear(
                    staffId,
                    Year.now().getValue()
            );

            // 处理未初始化记录的情况
            if (record == null) {
                // 自动创建记录
                AnnualLeave newRecord = new AnnualLeave(
                        staffId,
                        Year.now().getValue(),
                        calculateAnnualLeaveDays(staff.getBirthday()),
                        0
                );
                annualLeaveMapper.insert(newRecord);
                return new ResponseDTO(200, "初始化成功", newRecord.getTotalDays());
            }

            Integer remaining = record.getTotalDays() - record.getUsedDays();
            return new ResponseDTO(200, "查询成功", remaining);
        } catch (Exception e) {
            log.error("获取年休假余额异常 staffId={}", staffId, e); // 增加详细日志
            return new ResponseDTO(500, "服务器内部错误");
        }
    }


    // 新增扣减方法
    @Transactional
    public ResponseDTO deductAnnualLeave(Integer staffId, Integer days) {
        try {
            int currentYear = Year.now().getValue();
            // 原子操作：直接扣减并校验余额
            int affectedRows = annualLeaveMapper.deductDaysSafely(staffId, currentYear, days);

            if (affectedRows > 0) {
                return Response.success();
            }

            // 未成功扣减时查询具体原因
            AnnualLeave record = annualLeaveMapper.selectByStaffAndYear(staffId, currentYear);
            if (record == null) {
                return Response.error("未找到本年度年休假记录");
            }

            int remaining = record.getTotalDays() - record.getUsedDays();
            return Response.error("年休假余额不足，剩余天数：" + remaining);

        } catch (Exception e) {
            return Response.error("系统繁忙，请稍后重试");
        }
    }




    // 可选：手动调整年休假额度
    @Transactional
    public ResponseDTO adjustAnnualLeave(Integer staffId, Integer adjustDays) {
        try {
            AnnualLeave record = annualLeaveMapper.selectByStaffAndYear(
                    staffId,
                    Year.now().getValue()
            );

            if (record == null) {
                return new ResponseDTO(404, "未找到年休假记录");
            }

            if (record.getTotalDays() + adjustDays < 0) {
                return new ResponseDTO(400, "调整后天数不能为负数");
            }

            record.setTotalDays(record.getTotalDays() + adjustDays);
            annualLeaveMapper.updateById(record);

            return new ResponseDTO(200, "调整成功");
        } catch (Exception e) {
            log.error("调整年休假异常", e);
            return new ResponseDTO(500, "调整操作失败");
        }
    }
}

